// pages/shoppingMall/home.js
const app = getApp()
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "麓商城", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      isShare: 0,
    },
    requestUrl: app.baseUrl,
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    bannerArr: [],
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 500,
    tabArr: [],
    curTabId: "0",
    goodsList: [],
    btnText: "结算购物车",
    keywords: "",
    totalAmount: 0,
    totalNum: 0,
    showShoppingCart: false,
    shoppingCart: [],
    openid: '',
    shareTitle: '',
    shareImg: '',
    shop_id: 0,
    pageNum: 1, // 当前页码
    pageSize: 4, // 每页数量
    hasMore: 1, // 是否有更多数据
    isLoading: false, // 是否正在加载
    searchGoodsName: '', //搜索的商品名称

    is_login: 0,
    noRegisterContent: '',
    isOne: 1,
    flag: 0,
    searchDone: false
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  // 获取搜索框的值
  getKeywords(e) {
    var keywords = e.detail.value;
    this.setData({
      searchGoodsName: keywords
    })
  },
  searchClose() {
    let that = this;
    that.setData({
      searchDone: false,
      searchGoodsName: '',
      hasMore: 1,
    });
    var cateId = this.data.curTabId;
    that.setData({
      pageNum: 1
    });
    this.loadData(that.data.searchGoodsName, cateId, 1, 1);
  },
  //跳转商城卡包
  toCard() {
    //检查是否登录
    if (!this.checkLogin()) {
      return;
    }
    wx.navigateTo({
      url: '/pages/shoppingMall/cardList'
    });
  },
  //点击搜索
  search() {
    let searchGoodsName = this.data.searchGoodsName;
    if (searchGoodsName == '') {
      app.showTip('请输入搜索的商品名');
      return;
    }
    this.setData({
      searchGoodsName: searchGoodsName,
      hasMore: 1,
      pageNum: 1,
      searchDone: true
    })
    //调用加载
    var cateId = this.data.curTabId;
    this.loadData(searchGoodsName, cateId, 1, 1);
  },
  //点击分类
  chooseTab(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    that.setData({
      curTabId: id,
      hasMore: 1,
      pageNum: 1
    });
    //调用加载
    var searchGoodsName = this.data.searchGoodsName;
    var cateId = this.data.curTabId;
    this.loadData(searchGoodsName, cateId, 1, 1);
  },
  //检查是否登录
  checkLogin() {
    var that = this;
    //检查是否登录
    if (this.data.is_login == 0) {
      wx.showModal({
        title: '温馨提示',
        content: that.data.noRegisterContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/shoppingMall/home?shop_id=' + that.data.shop_id);
            wx.setStorageSync('loginHeaderType', 'redirectTo')
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/select-login/select-login'
              })
            }
          }
        }
      })
      return false;
    } else {
      return true;
    }
  },
  // 点击商品
  goDetail(e) {
    //检测是否注册登录
    if (!this.checkLogin()) {
      return;
    }
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/shoppingMall/detail?id=' + id,
    })
  },
  loadData(searchGoodsName, cateId, page, is_csh) {
    var that = this;
    //没有更多数据了
    if (!this.data.hasMore || this.data.isLoading) return;

    //请求后台加载更多
    this.setData({
      isLoading: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'shopLoadMore.php',
      method: 'POST',
      data: {
        'page': page,
        'shop_id': that.data.shop_id,
        'cateId': cateId,
        'searchGoodsName': searchGoodsName
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          if (is_csh == 1) {
            //需要初始化
            that.setData({
              goodsList: res.data.goodsList,
              hasMore: res.data.hasMore,
              isLoading: false,
              pageNum: that.data.pageNum + 1
            });
          } else {
            //不需要初始化 往后叠加
            const newList = res.data.goodsList;
            that.setData({
              goodsList: [...that.data.goodsList, ...newList],
              hasMore: res.data.hasMore,
              isLoading: false,
              pageNum: that.data.pageNum + 1
            });
          }
        }
      },
      fail: function () {}
    });
  },
  openShoppingCart() {
    let that = this;
    let shoppingCart = wx.getStorageSync('shoppingCart' + that.data.shop_id)
    if (shoppingCart.length > 0) {
      that.setData({
        showShoppingCart: true,
        showChildGoods: false,
        btnText: "结算购物车"
      })
    } else {
      app.showTip("现在购物中是空的哦！赶紧去选购吧")
    }

  },
  closeShoppingCart() {
    let that = this;
    that.setData({
      showShoppingCart: false,
    })
  },
  /**
   * 删除购物车中的商品
   * @param {Event} e - 触发事件的对象，包含当前商品的id
   * @description 该方法用于从购物车中移除指定的商品，并更新本地存储和页面数据
   * 1. 获取触发事件的商品id
   * 2. 查找购物车中对应商品的索引
   * 3. 如果找到商品，则从购物车数组中移除该商品
   * 4. 更新本地存储中的购物车数据
   * 5. 更新页面的购物车数据
   */
  delShoppingCartGoods(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let shoppingCart = that.data.shoppingCart;
    let shoppingCartIndex = shoppingCart.findIndex(item => item.id === id);
    if (shoppingCartIndex != -1) {
      shoppingCart.splice(shoppingCartIndex, 1);
      wx.setStorageSync('shoppingCart' + that.data.shop_id, shoppingCart)
      let totalAmount = shoppingCart.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
      let totalNum = shoppingCart.reduce((total, item) => total + item.num, 0);
      that.setData({
        shoppingCart,
        totalAmount,
        totalNum
      })
      if (shoppingCart.length < 1) {
        that.setData({
          totalAmount: 0,
          totalNum: 0,
          showShoppingCart: false
        })
      }
    }

  },
  //处理价格是整型还是浮点型数字
  gshNum(num) {
    if (!isNaN(num) && parseInt(num, 10) === parseFloat(num)) {
      //为整型
      return parseInt(num);
    } else {
      //为浮点型 保留两位小数
      return parseFloat(parseFloat(num).toFixed(2));
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var is_share = options.is_share;

    //获取商城id
    var shop_id = options.shop_id;
    if (shop_id == '' || shop_id == null || shop_id == undefined) {
      //看参数里是否存在shop_id
      shop_id = wx.getStorageSync('shop_id');
      if (shop_id == '' || shop_id == null || shop_id == undefined) {
        app.showTip('请先选择商城');
        setTimeout(function () {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
        return;
      }
    } else {
      wx.setStorageSync('shop_id', shop_id);
    }
    that.setData({
      shop_id: shop_id
    });

    //判断返回的跳转路径
    if (is_share == 1) {
      that.setData({
        ['defaultData.isShare']: 1
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getShoppingMailHomePageInfo(res.data.openid, 1, shop_id);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getShoppingMailHomePageInfo(openid, 1, shop_id);
    }

    //调用分享
    that.getShareInfo(shop_id);
  },

  //获取本页数据
  getShoppingMailHomePageInfo(openid, page, shop_id) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'getShoppingMailHomePageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'page': page,
        'shop_id': shop_id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          that.setData({
            bannerArr: res.data.bannerList,
            tabArr: res.data.cateList,
            goodsList: res.data.goodsList,
            hasMore: res.data.hasMore,
            is_login: res.data.is_login,
            noRegisterContent: res.data.noRegisterContent,
            pageNum: that.data.pageNum + 1
          });

          //重构购物车数据
          if (wx.getStorageSync('shoppingCart' + shop_id)) {
            let shoppingCart = wx.getStorageSync('shoppingCart' + shop_id);
            shoppingCart = that.delGqGoods(shoppingCart, res.data.carYxTime, shop_id);
            let totalAmount = shoppingCart.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
            let totalNum = shoppingCart.reduce((total, item) => total + item.num, 0);
            that.setData({
              shoppingCart,
              totalAmount,
              totalNum
            })
          }
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  //删除过期的购物车商品
  delGqGoods(carList, carYxTime, shop_id) {
    var that = this;
    var thisSjc = that.getThisSjc();

    for (var i = 0; i < carList.length; i++) {
      if (thisSjc - parseInt(carList[i].addSjc) >= parseInt(carYxTime)) {
        carList.splice(i, 1);
      }
    }
    //重新赋值购物车缓存中的商品
    wx.setStorageSync('shoppingCart' + shop_id, carList)
    return carList;
  },

  //获取当前时间戳
  getThisSjc() {
    let now = new Date();
    return Math.floor(now.getTime() / 1000);
  },

  //结算购物车
  pay() {
    var that = this;
    //判断是否登录
    if (!this.checkLogin()) {
      return;
    }

    //判断购物车中是否有商品
    if (this.data.shoppingCart.length <= 0) {
      app.showTip('购物车暂无商品哦');
      return;
    } else {
      for (let i = 0; i < this.data.shoppingCart.length; i++) {
        if (this.data.shoppingCart[i].inventory < this.data.shoppingCart[i].num) {
          app.showTip('您购物车中第' + [i + 1] + '件商品所选数量超过了库存数量');
          return;
        }
      }
    }

    //提交数据至订单
    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });
      wx.showLoading({
        title: '订单创建...',
        mask: true
      });

      //发起网络请求
      wx.request({
        url: that.data.baseUrl + 'addShopOrderInfo.php',
        method: 'POST',
        data: {
          'openid': that.data.openid,
          'shoppingCar': JSON.stringify(that.data.shoppingCart),
          'shop_id': that.data.shop_id,
          'totalAmount': that.data.totalAmount
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          app.showTip(res.data.msg);
          if (res.data.status == 1) {
            //清空购物车
            wx.setStorageSync('shoppingCart' + that.data.shop_id, []);
            that.setData({
              shoppingCart: [],
              totalAmount: 0,
              totalNum: 0
            });
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/shoppingMall/order?orderId=' + res.data.orderId + "&shop_id=" + that.data.shop_id
              });
            }, 1500);
          } else {
            if (res.data.is_show_del_tips == 1) {
              //删除购物车中特定id的商品
              var delCarList = res.data.delCarList;
              var shoppingCar = that.data.shoppingCart;
              var newShoppingCar = [];
              for (var i = 0; i < delCarList.length; i++) {
                for (var j = 0; j < shoppingCar.length; j++) {
                  if (parseInt(delCarList[i]) != parseInt(shoppingCar[j].id)) {
                    newShoppingCar.push(shoppingCar[j]);
                  }
                }
              }

              var totalAmount = newShoppingCar.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
              let totalNum = newShoppingCar.reduce((total, item) => total + item.num, 0);
              that.setData({
                shoppingCart: newShoppingCar,
                totalAmount: totalAmount,
                totalNum: totalNum
              });
              //更新缓存
              wx.setStorageSync('shoppingCart' + that.data.shop_id, newShoppingCar);
            }
          }
          that.setData({
            flag: 0
          });
          return;
        },
        fail: function () {
          that.setData({
            flag: 0
          });
          wx.hideLoading();
          return;
        }
      });
    }
  },

  //获取微信分享信息
  getShareInfo(shop_id) {
    var that = this;
    var id = 0;
    if (shop_id == 1) {
      id = 42;
    } else if (shop_id == 2) {
      id = 43;
    } else {
      id = 44;
    }
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {
        id: id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    if (that.data.isOne == 0) {
      //重构购物车数据
      if (wx.getStorageSync('shoppingCart' + that.data.shop_id)) {
        let shoppingCart = wx.getStorageSync('shoppingCart' + that.data.shop_id);
        shoppingCart = that.delGqGoods(shoppingCart, that.data.carYxTime, that.data.shop_id);
        let totalAmount = shoppingCart.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
        let totalNum = shoppingCart.reduce((total, item) => total + item.num, 0);
        that.setData({
          shoppingCart,
          totalAmount,
          totalNum
        })
      }
    } else {
      that.setData({
        isOne: 0
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    var searchGoodsName = this.data.searchGoodsName;
    var cateId = this.data.curTabId;
    var page = this.data.pageNum;
    this.loadData(searchGoodsName, cateId, page, 0);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/shoppingMall/home?shop_id=' + that.data.shop_id,
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})